//
// Define class HttpServer.
//

#ifndef __HTTP__SERVER__H
#define __HTTP__SERVER__H

#include <boost/function.hpp>

#include "core/tcp_server.h"
#include "core/base/noncopyable.h"
#include "core/base/time_tick.h"

namespace core {

class EventLoopThreadGroup;
class InetAddress;
class TCPConnection;
class TimestampMillisecond;

}  // namespace core

namespace demo {

class HttpContext;
class HttpRequest;
class HttpResponse;

class HttpServer : public core::Noncopyable {
 public:
  typedef boost::function<void (const HttpRequest&,
      HttpResponse*)> HttpCallback;

  HttpServer(const core::InetAddress &address, const std::string &name);
  ~HttpServer();

  inline void SetHttpCallback(const HttpCallback &callback) {
    this->http_callback_ = callback;
  }

  bool Initialize();
  void Start();

 private:
  void OnConnection(core::TCPConnection *connection);
  void OnMessage(core::TCPConnection *connection,
      core::ByteBufferDynamic &buffer, const core::TimeTick &time_tick);
  void OnWriteComplete(core::TCPConnection *connection);

  bool ProcessRequestLine(const char* begin, const char* end,
      HttpContext* context);
  bool ParseRequest(core::ByteBufferDynamic *buf, HttpContext* context,
      const core::TimestampMillisecond& timestamp);

  core::EventLoopThreadGroup *thread_pool_;
  HttpCallback http_callback_;
  core::TCPServer server_;

  static const char kCRLF[];
};

}  // namespace deom

#endif  // __HTTP__SERVER__H

